<template>
	<view class="content">
		<view class="search u-sticky">
			<uni-search-bar
				v-model="keyword"
				@input="search"
				:radius="100"
				cancelButton="none"
				placeholder="App名称或交互名称，如微信，聊天界面"
			></uni-search-bar>
		</view>
		<view class="waterfallsFlow">
			<waterfallsFlow
				ref="waterfallsFlow"
				imageSrcKey="small_url"
				:single="true"
				:list="list"
				@image-click="handleImg"
				@image-load="imgLoad"
			/>
		</view>
		<view class="list_loading" v-if="list.length <= 0 && listLoading"><u-loading-icon></u-loading-icon></view>
		<view class="more_loading"><uni-load-more v-if="showLoading" :status="moreLoading"></uni-load-more></view>
		<view class="empty" v-if="list.length <= 0"><u-empty mode="data"></u-empty></view>
	</view>
</template>

<script>
import api from '@/common/api.js';
import waterfallsFlow from '@/components/maramlee-waterfalls-flow/maramlee-waterfalls-flow.vue';
export default {
	components: {
		waterfallsFlow
	},
	data() {
		return {
			list: [],
			// proUrl: 'https://api.protograph.cn/', // 正式服地址
			page: 1,
			limit: 10,
			keyword: '',
			timeout: null,
			listLoading: false,
			showLoading: false,
			moreLoading: 'more'
		};
	},
	onLoad(option) {
		// console.log(option);
		if (option.tag) {
			this.keyword = option.tag;
			this.search();
		} else {
			this.getTags();
			this.getAssets();
			this.getNewFolder();
			this.getAllFolder();
		}
	},
	onPullDownRefresh() {
		this.$refs.waterfallsFlow.refresh();
		this.list = [];
		this.page = 1;
		this.getAssets();
	},
	// 触底触发
	onReachBottom() {
		if (this.list.length >= this.limit && !this.showLoading) {
			console.log('触底');
			this.page++;
			this.showLoading = true;
			this.moreLoading = 'loading';
			this.getAssets();
		}
	},
	onShareAppMessage(res) {
		if (res.from === 'button') {
			// 来自页面内分享按钮
			console.log(res.target);
		}
		return {
			title: '最全的APP截图收集站',
			path: '/pages/index/index'
		};
	},
	computed: {
		isLogin() {
			return this.$store.state.isLogin;
		}
	},
	watch: {
		isLogin: {
			handler(val) {
				console.log('登录状态改变');
				if (val) {
					this.list = [];
					this.page = 1;
					this.getAssets();
					this.getNewFolder();
					this.getAllFolder();
				}
			}
		}
	},
	methods: {
		handleImg(e) {
			// console.log('img ==>', e.item);
			// let activeIndex = 0;
			// let ids = this.list.map(item => {
			// 	return item.id
			// })
			// activeIndex = ids.indexOf(e.id);
			// console.log('activeIndex ==>', activeIndex);
			let list = this.list.slice(e.item.index - 6 < 0 ? 0 : e.item.index - 6);
			let active = 0;
			list.forEach((item, index) => {
				if (item.id == e.item.id) {
					active = index;
				}
			});
			// active = e.item.index;
			// console.log('最终列表 ==>', list);
			// uni.$off('handleImg');
			// setTimeout(() => {
			// 	uni.$emit('handleImg', { imgData: e.item, imgList: list });
			// }, 500);
			uni.navigateTo({
				url: `../../components/ImageDetail2/ImageDetail2?active=${active}`,
				animationType: 'slide-out-right',
				success: res => {
					res.eventChannel.emit('handleImg', { imgData: e.item, imgList: list });
				}
			});
		},

		imgLoad(e) {
			// console.log('imgLoad ==>', e);
		},

		// 获取所有标签
		async getTags() {
			try {
				let res = await this.$ajax({
					url: api.tags
				});
				// console.log('resTags ==>', res);
				let data = res.data.data;

				let categories = [];
				let platforms = [];
				categories = data.tag_categories[2].tags.map(item => {
					return {
						name: item.name,
						id: item.id
					};
				});
				platforms = data.tag_categories[0].tags.map(item => {
					return {
						name: item.name,
						id: item.id
					};
				});
				getApp().globalData.assetTags = data.asset_tags;
				getApp().globalData.categories = categories;
				getApp().globalData.platforms = platforms;
			} catch (e) {
				console.log(e);
			}
		},

		// 获取最新收藏夹
		async getNewFolder() {
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				return false;
			}
			try {
				let res = await this.$ajax.get({
					url: api.newest_favorites,
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('最新收藏夹res ==>', res);
				let data = res.data.data;
				data.forEach(item => {
					if (item.cover_path) {
						item.cover_path = JSON.parse(item.cover_path);
					}
				});
				if (res.statusCode == 200) {
					this.$store.commit('getNewFolder', data || []);
				}
			} catch (e) {
				console.log(e);
			}
		},

		// 获取全部收藏夹
		async getAllFolder() {
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				return false;
			}
			try {
				let res = await this.$ajax.get({
					url: api.favoriteFolders,
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('全部收藏夹res ==>', res);
				let data = res.data.data;
				data.forEach(item => {
					if (item.cover_path) {
						item.cover_path = JSON.parse(item.cover_path);
					}
				});
				if (res.statusCode == 200) {
					this.$store.commit('getAllFolder', data || []);
				}
			} catch (e) {
				console.log(e);
			}
		},

		// 搜索
		search() {
			clearTimeout(this.timeout);
			this.timeout = setTimeout(() => {
				this.list = [];
				this.page = 1;
				this.$refs.waterfallsFlow.refresh();
				this.getAssets();
			}, 500);
		},

		async getAssets() {
			// console.log('page ==>', this.page);
			this.listLoading = true;
			let url = "";
			let tokenString = uni.getStorageSync('access_token');
			if (tokenString) {
				url = api.assetsToken;
			} else {
				url = api.assets;
			}
			try {
				let res = await this.$ajax({
					url,
					data: {
						_page: this.page,
						_limit: this.limit,
						_sort: 'created_at',
						_order: 'desc',
						_keyword: this.keyword
					},
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('图片列表 ==>', res);
				if (res.statusCode == '200') {
					let data = res.data.data;
					data.forEach((item, index) => {
						// if (item.url.includes('2022')) {
						// 	item.small_url = this.$baseURL + '/' + item.small_url;
						// 	item.url = this.$baseURL + '/' + item.url;
						// } else {
						// 	item.small_url = this.proUrl + item.small_url;
						// 	item.url = this.proUrl + item.url;
						// }
						item.small_url = this.$baseURL + item.small_url;
						item.medium_url = this.$baseURL + item.medium_url;
						item.big_url = this.$baseURL + item.big_url;
					});
					this.list.push(...data);
					// console.log('list ==>', this.list);
					if (data.length < this.limit) {
						this.moreLoading = 'noMore';
					} else {
						this.showLoading = false;
					}
					this.listLoading = false;
					uni.stopPullDownRefresh();
				}
			} catch (e) {
				console.log(e);
				this.listLoading = false;
				this.showLoading = false;
				uni.stopPullDownRefresh();
			}
		}
	}
};
</script>

<style lang="scss">
.content {
	min-height: 100vh;
	padding: 0 20rpx;
	// background-color: #f5f5f5;

	.search {
		position: sticky;
		top: 0;
		z-index: 999;
		width: 100%;
		margin-bottom: 20rpx;
		// background-color: #f5f5f5;
	}
	.waterfallsFlow {
		// min-height: 100vh;
	}
	.list_loading {
		height: calc(100vh - 132rpx);
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.more_loading {
		height: 80rpx;
		padding: 20rpx 0;
	}
}
</style>
